var express = require('express');
var router = express.Router();
var querySql=require('../db/index')
// md5的引入
const {PWD_SALT,PRIVATE_KEY,EXPIRESD} = require('../utils/constant')
// 引入md5的加密方法
const {md5,upload}=require('../utils/index')
// 引用jwt 登录成功后服务器使用签名密钥生成JWT，并返回JWT给客户端
const jwt = require('jsonwebtoken')

/* 注册接口 */
router.post('/register', async(req, res, next) => {
    let {username,password,nickname, phone} = req.body
    try {
        let user = await querySql('select * from sys_user where username = ?',[username])
        if(!user || user.length === 0){
            password = md5(`${password}${PWD_SALT}`)
            await querySql('insert into sys_user(username,password,nickname, phone) value(?,?,?,?)',[username,password,nickname,phone])
            res.send({code:0,msg:'注册成功'})
        }else{
            res.send({code:-1,msg:'该账号已注册'})
        }
    }catch(e){
        console.log(e)
        next(e)
    }
});

// 登录接口
router.post('/login',async(req,res,next) => {
    let {username,password} = req.body
    try {
        let user = await querySql('select * from sys_user where username = ?',[username])
        if(!user || user.length === 0){
            res.send({code:-1,msg:'该账号不存在'})
        }else{
            password = md5(`${password}${PWD_SALT}`)
            let result = await querySql('select * from sys_user where username = ? and password = ?',[username,password])
            if(!result || result.length === 0){
                res.send({code:-1,msg:'账号或者密码不正确'})
            }else{
                let token = jwt.sign({username},PRIVATE_KEY,{expiresIn:EXPIRESD})
                res.send({code:0,msg:'登录成功',token:token})
            }
        }
    }catch(e){
        console.log(e)
        next(e)
    }
})



module.exports = router;
